
// 观察者模式 DOM事件监听
// function handler(ev: MouseEvent) {
//   console.log(ev);
// }
// document.body.addEventListener('click', handler)



class Producer{
  observers: Observer[]
  constructor(){
    this.observers = []
  }
  addListener(observer: Observer) {
    this.observers.push(observer)
  }
  removeListener(observer:Observer) {
    this.observers.splice(this.observers.indexOf(observer), 1)
  }
  notify(message: string) {
    this.observers.forEach(observer => {
      observer.update(message)
    })
  }
}

class Observer{
  name: string
  constructor(name: string) {
    this.name = name
  }
  update(message: string) {
    console.log(`${this.name}->${message}`);
  }
}

const subject = new Producer()



export {Producer,  Observer}


// 建立迭代器
// const createIterator = (data: any[]) => {
//   let nextIndex= 0

//   return {
//     hasNext: () => nextIndex < data.length,
//     next: () => data[nextIndex++]
//   }
// }

// const iterator = createIterator(['a', 'b', 'c', 'd'])

// while(iterator.hasNext()){
//   const value = iterator.next()
//   console.log(value);
// }


const createIterator = (data: any[]) => {
  let nextIndex = 0;

  return {
   [Symbol.iterator]: () => {
   	if(nextIndex < data.length){
    		return {
    			value: data[nextIndex++],
          done: false
    		}
    	} else {
    		 return {
         	done: true,
         	value:void 0
         };
    	}
   }
  };
};


const iterator = createIterator(['a', 'b', 'c', 'd'])
console.log(iterator);


class MyIterator{
  private arr: any[]
  private cursor: number
	constructor(arr: any[]) {
		this.arr = arr
		this.cursor = 0
	}
	next(){
		return this.cursor < this.arr.length ? { value:this.arr[this.cursor++], done:false} : {done:true, value:void 0}
	}
  map(cb: (val:number) =>{}) {
    const iterator = new MyIterator(this.arr)
    return {
      next: () => {
        const {done, value} = iterator.next()
        return {
          done,
          value: done ? 0 : cb(value)
        }
      }
    }
  }
}


function * getCount(words:string) {
  for (const word of words) {
    if(/[A-Z]+$/.test(word)){
      yield word
   }
  }
}


const strinter = getCount('RxJS训练营')
// strinter.next()
// //{value: "R", done: false}
// strinter.next()
// //{value: "J", done: false}
// strinter.next()
// //{value: "S", done: false}
// strinter.next()

